package com.cartoonrabbit.config.security.filter;

import cn.hutool.http.HttpStatus;
import com.cartoonrabbit.config.exception.ServiceException;
import com.cartoonrabbit.config.redis.utils.RedisCache;
import com.cartoonrabbit.config.security.pojo.LoginUser;
import com.cartoonrabbit.config.security.utils.JwtTokenUtil;
import com.cartoonrabbit.pojo.User;
import com.cartoonrabbit.service.IUserService;
import com.cartoonrabbit.wxapp.properties.WxAppJwtProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * jwt登录授权过滤器
 */
@Component
public class JwtAuthencationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private IUserService userService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private WxAppJwtProperties wxAppJwtProperties;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 打印日志

        //获取token的key
        String tokenKey = request.getHeader(wxAppJwtProperties.getTokenHeader());

        //判断tokenkey
        if(StringUtils.isEmpty(tokenKey)){
            filterChain.doFilter(request,response);
            return;
        }

        //根据tokenkey获取token
        Object tokenObject = redisCache.getCacheObject(tokenKey);
        if (ObjectUtils.isEmpty(tokenObject)){
            throw new ServiceException("token过期，请重新登录", 403);
        }

       String token = (String) tokenObject;


        String openId;
        try {
            openId = jwtTokenUtil.getUsernameByToken(token);
        }catch (Exception e){
            throw new ServiceException("token非法", 403);
        }

        //从数据库中获取用户信息
        User user = userService.getUserInfoByOpenId(openId);

        if (ObjectUtils.isEmpty(user)){
            filterChain.doFilter(request,response);
            return;
        }

        LoginUser loginUser = new LoginUser(user);
        //验证token是否有效
        if (!jwtTokenUtil.validateToken(token,loginUser)){
            throw new ServiceException("token过期，请重新登录", HttpStatus.HTTP_INTERNAL_ERROR);
        }

        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        //存人SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);

    }
}
